<template>
  <div class="page-box">
    <div class="page-title fonsSizeTitle">考核季度：{{quarterInfo.title}}</div>
    <rulePart />
    <div class="work-box">
      <div class="work-box-title  fonsSizeTitle">工作绩效（占比60%）</div>
      <div v-for="(item,index) of from" :key="index" class="work">
        <van-cell-group>
          <van-field @change="localStorageSetItem()" required v-model.trim="item.question_name" label="考核标准 " type="textarea" placeholder="请输入考核标准" rows="1" autosize />
        </van-cell-group>
        <van-cell-group>
          <van-field @change="localStorageSetItem()" required v-model.trim="item.task" label="考核内容 " type="textarea" placeholder="请输入关键绩效" rows="3" autosize />
        </van-cell-group>
        <van-cell-group>
          <van-field @change="rareChange(item.rare,index)" required v-model.trim="item.rare" label="百分比 " type="number" placeholder="请输入1-60之间的数字">
            <van-button @click="deleteFromItem(index)" v-if="index!=0" slot="button" size="small" icon="delete" type="danger"></van-button>
          </van-field>
        </van-cell-group>
      </div>
      <van-button class="cursor" @click="addFromItem()" style="width:80%;margin:26px 10% " type="primary" icon="plus">继续添加</van-button>
    </div>
    <div class="screen_fixed cenCen">
      <van-button class="cursor maxWidth" @click="submitFrom()" style="width:100%" icon="success" type="info">提交审核</van-button>
    </div>
  </div>
</template>
<script>
import rulePart from "@/components/assembly/rulePart"; //写死规定
import rulePartData from "@/components/assembly/rulePartData.js";
import service from "@/api";
import { quarterTime } from "@/components/js/quarterTime";
export default {
  components: { rulePart },
  data() {
    return {
      query: {},
      quarterInfo: {}, //季度信息
      // 提交审核
      fromItem: {
        // 表单每一项的格式
        question_name: "", //考核标准
        task: "", //内容
        rare: "" //考核占比
        // question_name: "考核标准", //考核标准
        // task: "内容", //内容
        // rare: 60 //考核占比
      },
      from: [] //填写的表单
    };
  },
  created() {
    this.query = this.$route.query || {};
    // console.log(localStorage.getItem("enterKaoHeFrom"));
    if (localStorage.getItem("enterKaoHeFrom")) {
      // 缓存相关
      this.from = JSON.parse(localStorage.getItem("enterKaoHeFrom"));
    } else {
      // 默认添加一项
      this.addFromItem();
    }
    // this.localStorage();
    this.quarter_listAll();
    // 如果是编辑则查询一下
    if (this.query.id !== undefined) {
      this.examine_findById();
    }
  },
  methods: {
    // 获取当前季度信息
    async examine_findById() {
      this.$store.state.loading = true;
      this.$store.state.loadingText = "获取数据中";
      const { data = {} } = await service.examine_findById({
        id: this.query.id
      });
      this.$store.state.loading = false;
      this.from = [];
      data.examineList.map(item => {
        if (item.question_type == 2) {
          // 只添加不是写死部分
          this.from.push(item);
        }
      });
    },
    // 本地存储数据
    localStorageSetItem() {
      localStorage.setItem("enterKaoHeFrom", JSON.stringify(this.from));
    },
    // 获取当前季度信息
    async quarter_listAll() {
      this.$store.state.loading = true;
      this.$store.state.loadingText = "获取数据中";
      const { data = {} } = await service.quarter_listAll({});
      if (data.rows && data.rows.length) {
        this.quarterInfo = data.rows[0];
        this.quarterInfo.title = `${quarterTime(
          this.quarterInfo.start_date,
          this.quarterInfo.end_date
        )} ${this.quarterInfo.name}`;
      }
      this.$store.state.loading = false;
    },
    rareChange(rare, index) {
      if (rare < 1 || rare > 60) {
        this.$toast.fail(`请输入1-60之间的数字`);
        this.from[index].rare = 1;
        return;
      }
      this.localStorageSetItem();
    },
    //添加审核标准
    async addFromItem() {
      const checkFromRes = await this.checkFrom(this.from);
      if (!checkFromRes.isPass) {
        this.$toast.fail(checkFromRes.errorMsg);
        return;
      }
      if (checkFromRes.rareSum >= 60 || checkFromRes.rareSum < 0) {
        this.$toast.fail(
          `工作绩效（占比60%）请确定百分比，当前是${checkFromRes.rareSum}%`
        );
        return;
      }
      this.from.push(JSON.parse(JSON.stringify(this.fromItem)));
    },
    //删除审核标准
    async deleteFromItem(index) {
      const alertRes = await this.$alert("此操作将进行删除");
      if (!alertRes) {
        return;
      }
      this.from.splice(index, 1);
      this.localStorageSetItem();
    },
    // 提交表单
    async submitFrom() {
      const checkFromRes = await this.checkFrom(this.from);
      if (!checkFromRes.isPass) {
        this.$toast.fail(checkFromRes.errorMsg);
        return;
      }

      if (checkFromRes.rareSum != 60) {
        this.$toast.fail(
          `工作绩效（占比60%）请确定百分比，当前是${checkFromRes.rareSum}%`
        );
        return;
      }
      const alertRes = await this.$alert("此操作将进行审核提交");
      if (!alertRes) {
        return;
      }

      let subData = {
        quarter_id: this.quarterInfo.id,
        quarter_name: this.quarterInfo.title,
        examineList: ""
      };

      let examineList = [];
      // 添加价值观部分
      rulePartData.map((item, index) => {
        let obj = {
          question_code: index, //题目编码索引
          question_type: 1, //1-价值观，2-工作绩效
          question_name: item.title, //考核标准
          task: item.con, //考核内容
          rare: item.rare
        };
        // item.con.map(itemCon => {
        //   obj.task += `${itemCon}`;
        // });
        examineList.push(obj);
      });

      // 添加工作绩效
      this.from.map((item, index) => {
        let obj = {
          question_code: examineList.length + index, //题目编码索引
          question_type: 2, //1-价值观，2-工作绩效
          question_name: item.question_name, //考核标准
          task: item.task, //考核内容
          rare: item.rare
        };
        examineList.push(obj);
      });
      console.log(examineList);
      subData.examineList = JSON.stringify(examineList);
      console.log(subData);
      this.$store.state.loading = true;
      this.$store.state.loadingText = "提交数据中";
      let success = false;
      if (this.query.id !== undefined) {
        // 如果是编辑
        subData.id = this.query.id;
        success = (await service.examine_edit(subData)).success;
      } else {
        success = (await service.examine_save(subData)).success;
      }
      this.$store.state.loading = false;
      if (success) {
        localStorage.removeItem("enterKaoHeFrom");
        this.$toast.success("提交成功");
        this.$goBack();
      }
    },

    // 检查表单
    checkFrom(arr) {
      let value = {
        isPass: true,
        rareSum: 0,
        errorMsg: ""
      };
      for (let i = 0; i < arr.length; i++) {
        const { question_name, task, rare } = arr[i];
        if (!question_name) {
          value.isPass = false;
          value.errorMsg = "请输入考核标准";
          break;
        }
        if (!task) {
          value.isPass = false;
          value.errorMsg = "请输入考核内容";
          break;
        }
        if (!rare) {
          value.isPass = false;
          value.errorMsg = "请输入百分比";
          break;
        }
        if (rare < 1 || rare > 60) {
          value.isPass = false;
          value.errorMsg = "请输入1-60之间的数字(百分比)";
          break;
        }
        value.rareSum += Number(rare);
      }
      return new Promise(resolve => {
        resolve(value);
      });
    }
  }
};
</script>

<style scoped>
@import "./../../../components/public.css";
</style>